/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 *
 */

import fs from 'fs';
import os from 'os';
import path from 'path';
import process from 'process';

import { expect } from '@jest/globals';
import fse from 'fs-extra';

import { runHvigorAsync } from '../../common/common';
import { commonFileOperation } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: [ModuleTemplateType.SharedLibrary],
};

const testfun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();

  // hvigor-ohos-online-sign-plugin目录链接到node_modules
  const IS_WINDOWS = process.platform === 'win32' || os.type() === 'Windows_NT';
  const hvigorMonorepoPath = path.resolve(require.resolve('@ohos/hvigor-ohos-plugin'), '../../../');
  const dir = path.resolve(hvigorMonorepoPath, 'packages', 'hvigor-ohos-online-sign-plugin');
  const target = path.resolve(hvigorMonorepoPath, 'node_modules', '@ohos', 'hvigor-ohos-online-sign-plugin');
  if (!fse.existsSync(target)) {
    fs.symlinkSync(dir, target, IS_WINDOWS ? 'junction' : 'dir');
  }

  // 这里的签名材料不用配置正确
  await commonFileOperation(path.resolve(projectRootPath, 'hvigorfile.ts'), async (json) => {
    return `// 系统插件
            import { appTasks } from '@ohos/hvigor-ohos-plugin';
            // 1. 导入在线签名插件
            import { onlineSignPlugin } from '@ohos/hvigor-ohos-online-sign-plugin';
            import type { OnlineSignOptions } from '@ohos/hvigor-ohos-online-sign-plugin';

            // 2. 配置签名参数
            const signOptions: OnlineSignOptions = {
                profile: 'hw_sign/debug.p7b',           // 签名材料
                keyAlias: 'HOS Application Provision Debug V2',
                hapSignToolFile: 'hw_sign/hap-sign-tool.jar',      // 签名工具hap-sign-tool.jar的路径
                username: '11111',  // 环境变量中需要配置用户名和密码
                password: '22222',
                enableOnlineSign: true                  // 是否启用在线签名
            }

            // hvigorfile 导出范式
            export default {
                system: appTasks,
                plugins:[
                // 3. 应用插件
                    onlineSignPlugin(signOptions)
                ]
            }`;
  });
  const commands: string[] = '--mode project -p product=default assembleApp --analyze=normal --parallel --incremental --no-daemon --stacktrace'.split(' ');
  const result = await runHvigorAsync(projectRootPath, commands);
  record.addStep('1. 配置签名，构建entry', result);
  // 构建只需要保证在线签名的任务挂载上
  expect(result.stdout).toContain('entry:default@onlineSignHap');
  expect(result.stdout).toContain('shareLibrary:default@onlineSignHsp');
  expect(result.stdout).toContain('onlineSignApp');
};

TestCaseBuilder.builder()
  .caseName('ONLINE_SGIN_PLUGIN')
  .description('看护在线签名插件')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L0).build())
  .testFun(testfun)
  .load();
